package net.kleinhenz.questor.ui;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import net.kleinhenz.questor.Questor;
import net.kleinhenz.questor.R;
import net.kleinhenz.questor.system.QSRFile;
import android.app.TabActivity;
import android.content.Intent;
import android.database.DataSetObserver;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class StorySelectorActivity extends TabActivity implements ListAdapter, OnItemClickListener
{
	public static final String EXTRA_URL_STRING = "URL_STRING";
	private List<QSREntry> qsrFiles = null;
	
	public class QSREntry 
	{
		public String url = null;
		public QSRFile qsrFile = null;
	
		public QSREntry(String url, QSRFile qsrFile)
		{
			this.url = url;
			this.qsrFile = qsrFile;
		}
	}
	
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);

	    Log.i(Questor.APP_NAME, "Selecting story file.");

	    // search sd card for files
	    try
		{
	    	qsrFiles = searchSDCard();
		}
		catch (IOException e)
		{
			throw new RuntimeException(e);
		}
	    
	    setContentView(R.layout.storyselector);

        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);  

	    TabHost mTabHost = getTabHost();
	    
	    mTabHost.addTab(mTabHost.newTabSpec("tab_local").setIndicator("Device", getResources().getDrawable(android.R.drawable.ic_input_get)).setContent(R.id.locallist));
	    mTabHost.addTab(mTabHost.newTabSpec("tab_network").setIndicator("Internet", getResources().getDrawable(android.R.drawable.ic_lock_lock)).setContent(R.id.networklist));
	    mTabHost.setCurrentTab(0);

	    ListView localList = (ListView)findViewById(R.id.locallist);

	    localList.setAdapter(this);

	    localList.setClickable(true);
	    localList.setOnItemClickListener(this);
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
	{
		String url = qsrFiles.get(arg2).url;
		
		Intent intent = new Intent();
		intent.putExtra(StorySelectorActivity.EXTRA_URL_STRING, url);
		setResult(Questor.REQ_STORYSELECT, intent);
		finish();
	}

	protected List<QSREntry> searchSDCard() throws IOException
	{
	    Log.i(Questor.APP_NAME, "Starting card scanning.");

	    List<QSREntry> files = new ArrayList<QSREntry>();
	
		for (File file : new File("/sdcard/questor").listFiles())
			if (file.isFile() && file.getAbsolutePath().endsWith(".qsr"))
				files.add(new QSREntry("file:" + file.getAbsolutePath(), new QSRFile(getCacheDir(), new File(file.getAbsolutePath()))));

	    Log.i(Questor.APP_NAME, "Card scanning finished.");

		return files;
	}

	private View createListEntryView(int position) throws FileNotFoundException, IOException
	{
	    Log.i(Questor.APP_NAME, "Creating list entry for entry " + position);

	    QSREntry entry = qsrFiles.get(position);
		Questor.setCurrentLoadQSR(entry.qsrFile);
		
		View listEntryView = View.inflate(this, R.layout.storyselectorentry, null);		
		
		BufferedReader reader = new BufferedReader(new FileReader(entry.qsrFile.getFile("/abstract.html")));
		StringBuffer abstractText = new StringBuffer();
		
		int data = -1;
		while ((data=reader.read())!=-1)
			abstractText.append((char)data);
		reader.close();		

		TextView gameTextView = (TextView)listEntryView.findViewById(R.id.gametext);
		CharSequence styledText = Html.fromHtml(abstractText.toString()); 
		gameTextView.setText(styledText);

		InputStream imageStream = entry.qsrFile.getInputStream("/abstract.png");
		Bitmap iconBitmap = BitmapFactory.decodeStream(imageStream);
		imageStream.close();		

		ImageView gameIcon = (ImageView)listEntryView.findViewById(R.id.gameicon);
		gameIcon.setImageBitmap(iconBitmap);

	    Log.i(Questor.APP_NAME, "Finished creating list entry for entry " + position);

		return listEntryView;
	}
	
	// List Adapter methods
	
	@Override
	public int getCount()
	{
		return qsrFiles.size();
	}

	@Override
	public Object getItem(int position)
	{
		return qsrFiles.get(position);
	}

	@Override
	public long getItemId(int position)
	{
		return position;
	}
	
	@Override
	public View getView(int position, View convertView, ViewGroup parent)
	{
		try
		{
			return createListEntryView(position);
		}
		catch (FileNotFoundException e)
		{
			throw new RuntimeException(e);
		}
		catch (IOException e)
		{
			throw new RuntimeException(e);
		}
	}

	@Override
	public boolean areAllItemsEnabled()
	{
		return true;
	}

	@Override
	public boolean isEnabled(int arg0)
	{
		return true;
	}

	@Override
	public int getItemViewType(int arg0)
	{
		return 0;
	}

	@Override
	public int getViewTypeCount()
	{
		return 1;
	}

	@Override
	public boolean hasStableIds()
	{
		return true;
	}

	@Override
	public boolean isEmpty()
	{
		return false;
	}

	@Override
	public void registerDataSetObserver(DataSetObserver observer)
	{
		// NOP
	}

	@Override
	public void unregisterDataSetObserver(DataSetObserver observer)
	{
		// NOP
	}
}
